﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{

    public bool isAI = false;

    public IUserInput playerInput;

    private GameObject cameraHandle;
    private GameObject playerHandle;
    private GameObject model;
    [SerializeField]
    private GameObject lockTarget;

    private float eulerX;

    void Start()
    {
        cameraHandle = transform.parent.gameObject;
        playerHandle = cameraHandle.transform.parent.gameObject;
        ActorController ac = playerHandle.GetComponent<ActorController>();
        model = ac.model;
        playerInput = ac.playerInput;
        eulerX = 20.0f;
    }    

    // Update is called once per frame
    void FixedUpdate()
    {

        if (lockTarget == null) {
            Vector3 tempEulerAngle = model.transform.eulerAngles;
            playerHandle.transform.Rotate(Vector3.up, playerInput.Jright * 100.0f * Time.deltaTime);
            //cameraHandle.transform.Rotate(Vector3.right, playerInput.Jup * (-80) * Time.deltaTime);
            eulerX -= playerInput.Jup * 80 * Time.deltaTime;
            eulerX = Mathf.Clamp(eulerX, -40.0f, 30.0f);
            cameraHandle.transform.localEulerAngles = new Vector3(eulerX, 0, 0);
            model.transform.eulerAngles = tempEulerAngle;
        } else {
            Vector3 tempDir = lockTarget.transform.position - model.transform.position;
            tempDir.y = 0.0f;
            playerHandle.transform.forward = tempDir;
        }
    }

    public void LockUnlock() {
        Vector3 pos1 = model.transform.position;
        Vector3 pos2 = pos1 + new Vector3(0, 1, 0);
        Vector3 centerPos = pos2 + model.transform.forward * 5.0f;
        Collider[] colliders = Physics.OverlapBox(centerPos, new Vector3(0.5f, 0.5f, 5f), model.transform.rotation, LayerMask.GetMask("Enemy"));
        if (colliders.Length == 0) {
            lockTarget = null;
        } else {
            foreach (var col in colliders)
            {
                if (colliders[0].gameObject == lockTarget) {
                    lockTarget = null;
                    return;
                }
                lockTarget = colliders[0].gameObject;
                break;
            }
        }
    }
}
